package com.etouch.security.config.security;

import com.etouch.security.pojo.dto.SysRoleDTO;
import com.etouch.security.pojo.dto.SysUserDTO;
import com.etouch.security.pojo.entity.SysPermission;
import com.etouch.security.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 自定义的认证用户获取服务类
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserService sysUserService;

    /**
     * 根据用户名获取认证用户信息
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (StringUtils.isEmpty(username)) {
            throw new UsernameNotFoundException("UserDetailsService没有接收到用户账号");
        } else {
            //根据用户名查找用户信息
            SysUserDTO sysUserDTO = sysUserService.getUserByUserName(username);
            if (sysUserDTO == null) {
                throw new UsernameNotFoundException(String.format("用户不存在", username));
            }
            //新建权限集合
            List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
            //模拟从数据库获取角色权限
            List<SysRoleDTO> sysRoleDTOList = sysUserDTO.getSysRoleDTOList();
            for (SysRoleDTO sysRoleDTO : sysRoleDTOList) {
                //封装用户信息和角色信息到SecurityContextHolder全局缓存中
                grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_" + sysRoleDTO.getRoleName()));
//                //用户的权限信息
//                List<SysPermission> permissionList = sysRoleDTO.getPermissionList();
//                for (SysPermission sysPermission : permissionList) {
//                    grantedAuthorities.add(new UrlGrantedAuthority(sysPermission.getUrl(), sysPermission.getPermCode()));
//                }
            }

            //创建一个用于认证的用户对象并返回，包括：用户名，密码，角色
            return new User(sysUserDTO.getUsername(), sysUserDTO.getPassword(), grantedAuthorities);
        }
    }
}
